package example;

import java.io.*;
import java.util.Scanner;

public class FindByContent {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("输入你要查找的路径：");
        String filePath=scanner.nextLine();
        File file=new File(filePath);
        if(!file.isDirectory()){
            System.out.println("文件路径输入有误");
            return;
        }
        System.out.println("输入你要查找的文件内容的关键字：");
        String key=scanner.nextLine();
        scan(file, key);
    }
    public static void scan(File file,String key){
        if(!file.isDirectory()){
            return;
        }
        File[] files=file.listFiles();
        for(File f:files){
            if(f.isFile()){
                //找到文件是普通文件
                //执行文件内容查找
                doSearch(f,key);
            }else {
                //递归查询是目录的话，就继续递归查询文件信息
                scan(f,key);
            }
        }
    }
    public static void doSearch(File file,String key){
        if(!file.isFile()){
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(FileReader reader=new FileReader(file)){
            char[] buffer=new char[1024];
            while (true) {
                int n = reader.read(buffer);
                if (n == -1) {
                    break;
                }
                String s = new String(buffer, 0, n);
                stringBuilder.append(s);
            }
        }catch(IOException e){
            e.printStackTrace();
        }

        if(stringBuilder.toString().contains(key)){
            System.out.println(file.getAbsolutePath());
        }
    }
}
